<template>
    <el-input v-model="page.question" style="width: 240px" placeholder="根据题干查询" />
    <el-tree-select
          placeholder="选择阶段"
          :props="defaultProps"
          v-model="page.subId"
          :data="levels"
          :render-after-expand="false"
          style="width: 240px;"
        />
    <el-select
      v-model="page.typeId"
      placeholder="选择题型"
      style="width: 240px"
    >
      <el-option
        v-for="item in types"
        :label="item.typeName"
        :value="item.id"
      />
    </el-select>

    <el-button style="margin-left: 30px;" type="primary" icon="Search" @click="getData()" >搜索</el-button>
    <el-button :disabled="dels.length==0" icon="delete" type="danger" @click="delsQuestions()">
        删除选中内容
    </el-button>
    <el-button icon="Refresh" @click="resetQuery()">刷新</el-button>
    <el-button style="margin-left: 15px;" type="primary" icon="Download" @click="offQuest()" >导出试题</el-button>
    <el-table @selection-change="handleSelectionChange" v-loading="loading" :data="tableData" style="width: 100%;height: 575px;" :stripe="true">
         <el-table-column type="selection" width="55" />
        <el-table-column label="试题编号" prop="id" width="110"/>
        <el-table-column label="题型" width="120">
            <template #default="scope">
                <span v-if="scope.row.typeId==1">单选题</span>
                <span v-if="scope.row.typeId==2">多选题</span>
                <span v-if="scope.row.typeId==3">判断题</span>
                <span v-if="scope.row.typeId==4">简答题</span>
            </template>
        </el-table-column>
        <el-table-column label="题干" prop="question" width="280">
            <template #default="scope">
                <span class="answer-text">{{ scope.row.question.split("/")[0] }}</span>
            </template>
        </el-table-column>
        <el-table-column label="答案" width="350px">
            <template #default="scope">
                <span style="width: 300px;" class="answer-text">{{ scope.row.answerTxt }}</span>
            </template>
        </el-table-column>
        <el-table-column label="所属课程" prop="subjectName" width="120"/>
        <el-table-column  style="height: 30px;" label="状态" width="120">
            <template #default="scope">
                <el-tag v-if="scope.row.state==0"type="success">正常</el-tag>
                <el-tag v-else type="danger">下线</el-tag>
            </template>
        </el-table-column>


        <el-table-column>
        <template #default="scope">

            <el-popover
                placement="top"
                trigger="hover"
                content="查看试题详情"
            >
                <template #reference>
                    <el-icon class="hoverColor" @click="edit(scope.row)"><View /></el-icon>
                </template>
            </el-popover>

            <el-popover
                placement="top"
                trigger="hover"
                content="切换状态"
            >
                <template #reference>
                    <el-icon class="hoverColor" style="margin-left: 50px;"  @click="upStore(scope.row)"><Sort /></el-icon>
                </template>
            </el-popover>

        </template>
        </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="page.pageNum"
      v-model:page-size="page.pageSize"
      :page-sizes="[1, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
    v-model="editFlog"
    width="500"
  >
    <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
  >
    <el-form-item label="试题id: " prop="id">
      <el-input v-model="ruleForm.id" disabled/>
    </el-form-item>

    
    <el-form-item label="试题类型: " prop="question">
      <el-select
        v-model="ruleForm.typeId"
        placeholder="选择题型"
        style="width: 240px"
        >
        <el-option
            v-for="item in type"
            :label="item.typeName"
            :value="item.id"
            :disabled="item.disabled"
        />
        </el-select>
    </el-form-item>
    <el-form-item label="题干: " prop="question">
      <el-input type="textarea" v-if="ruleForm.typeId>2" placeholder="Please input" v-model="ruleForm.question" />
      <div v-else>
            <el-input type="textarea" placeholder="Please input" v-model="ruleForm.body" />
            <el-input placeholder="Please input" v-model="ruleForm.a" />
            <el-input placeholder="Please input" v-model="ruleForm.b" />
            <el-input placeholder="Please input" v-model="ruleForm.c" />
            <el-input placeholder="Please input" v-model="ruleForm.d" />
      </div>
      
    </el-form-item>
    <el-form-item label="答案: " prop="answerTxt">
      <el-input v-if="ruleForm.typeId==4" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" v-model="ruleForm.answerTxt" />
      <el-radio-group v-if="ruleForm.typeId==3" v-model="ruleForm.answerTxt" class="ml-4">
        <el-radio value="正确" size="large" style="color:green">正确</el-radio>
        <el-radio value="错误" size="large" style="color:red">错误</el-radio>
    </el-radio-group>
      <div v-if="ruleForm.typeId<=2">
        <el-select v-if="ruleForm.typeId!=2" v-model="ruleForm.answerTxt" placeholder="Select" style="width: 240px">
        <el-option
            v-for="item in abcd"
            :label="item.name"
            :value="item.value"
        />
        </el-select>
        <el-select v-else multiple v-model="ruleForm.sels" placeholder="Select" style="width: 240px">
        <el-option
            v-for="item in abcd"
            :label="item.name"
            :value="item.value"
        />
        </el-select>
      </div>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="upQuestion()">
        修改
      </el-button>
      <el-button type="danger" @click="delOne(ruleForm.id)">
        删除
      </el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
</template>
<script setup>
import { findAllQuestion,questionDelete,questionUpdate,findAllType,findAllLevel,download } from '@/api/admin/questions.js';
import { ref,onMounted,watch } from "vue";
import router from '@/router';
import { ElMessage } from 'element-plus'

const defaultProps = {
  children: 'slearningProgress',
  label: 'levelName',
}
const editFlog=ref(false)
const loading=ref(false)
const ruleForm=ref({})
const tableData=ref([])
const levels=ref([])
const types=ref([])
const type=ref([])
const dels=ref([])
const abcd=ref([
    {
        name:"A",
        value:"A"
    },
    {
        name:"B",
        value:"B"
    },
    {
        name:"C",
        value:"C"
    },
    {
        name:"D",
        value:"D"
    },
])


const page=ref({
    typeId:null,
    pageNum:1,
    pageSize:10
})

const offQuest = () => {
    download(page.value).then(res => {
        const blob = new Blob([res.data], { type: 'application/octet-stream' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'example.docx';
        a.click();
        URL.revokeObjectURL(url);
    });
}

const handleSelectionChange = (val) => {
  dels.value = val
}
const delsQuestions=()=>{
    dels.value.forEach(element => {
        delOne(element.id)
    });
}
const getData=()=>{
    loading.value=true
    findAllQuestion(page.value).then(res=>{
        tableData.value=res.data.obj.list
        page.value.total=res.data.obj.total
        loading.value=false
    })
} 
getData()


const resetQuery=()=>{
    page.value={
        typeId:null,
        pageNum:1,
        pageSize:10
    }
    getData()
}

const getLevel=()=>{
    findAllLevel().then(res=>{
        levels.value.push({
            levelName:"全部试题",
            value:null
        })
        res.data.obj.forEach(element1 => {
          element1.value=element1.id
          element1.slearningProgress.forEach(element2 => {
            element2.value=element2.id
            element2.levelName=element2.name
            element2.slearningProgress=element2.ssubjects
            element2.slearningProgress.forEach(element3 => {
              element3.levelName=element3.subjectName
              element3.value=element3.id
            });
          });
          levels.value.push(element1)
        });
    })
}
getLevel()

const delOne=(id)=>{
    questionDelete(id).then(res=>{
        ElMessage.success("删除成功")
        getData()
    })
}

const getType=()=>{
    findAllType().then(res=>{
        types.value.push({id:null,typeName:'全部题型'})
        res.data.obj.forEach(element => {
            types.value.push(element)
        });
        type.value=res.data.obj
    })
}
getType()

const edit=(row)=>{
    type.value[1]={typeName:" 多选题",id:2}
    type.value[0]={typeName:" 单选题",id:1}
    editFlog.value=true
    ruleForm.value=row
    if (ruleForm.value.answerTxt.length>4) {
        type.value[1]={typeName:" 多选题(答案长度过大 不能为多选题) 修改后请重新进入",id:2,disabled:true}
    }
    if (ruleForm.value.answerTxt.length>1) {
        type.value[0]={typeName:" 单选题(答案长度过大 不能为单选题) 修改后请重新进入",id:1,disabled:true}
    }
    ruleForm.value.sels=row.answerTxt.split('')
    ruleForm.value.body=ruleForm.value.question.split('/')[0]
    ruleForm.value.a=ruleForm.value.question.split('/')[1].split('_')[0]
    ruleForm.value.b=ruleForm.value.question.split('/')[1].split('_')[1]
    ruleForm.value.c=ruleForm.value.question.split('/')[1].split('_')[2]
    ruleForm.value.d=ruleForm.value.question.split('/')[1].split('_')[3]
}

const upQuestion=()=>{
    if (ruleForm.value.typeId<=2) {
        
        if (ruleForm.value.body==null||ruleForm.value.body=="") {
            ElMessage.error("题干不能为空")
        }else if(ruleForm.value.a==null||ruleForm.value.a==""){
            ElMessage.error("答案a不能为空")
        }else if(ruleForm.value.b==null||ruleForm.value.b==""){
            ElMessage.error("答案b不能为空")
        }else if(ruleForm.value.c==null||ruleForm.value.c==""){
            ElMessage.error("答案c不能为空")
        }else if(ruleForm.value.d==null||ruleForm.value.d==""){
            ElMessage.error("答案d不能为空")
        }else{
            ruleForm.value.question=ruleForm.value.body+"/"+ruleForm.value.a+"_"+ruleForm.value.b+"_"+ruleForm.value.c+"_"+ruleForm.value.d
            if (ruleForm.value.typeId==2) {
                var s=""
                ruleForm.value.sels.forEach(element => {
                    s+=element
                });
                ruleForm.value.answerTxt=s
            }
            questionUpdate(ruleForm.value).then(res=>{
                getData()
                editFlog.value=false
                ElMessage.success("修改成功")
            })
            }
        }else{
            if (ruleForm.value.question==null||ruleForm.value.question=="") {
                ElMessage.error("题干不能为空")
            }else if (ruleForm.value.answerTxt==null||ruleForm.value.answerTxt=="") {
                ElMessage.error("答案不能为空")
            }else{
                questionUpdate(ruleForm.value).then(res=>{
                    getData()
                    editFlog.value=false
                    ElMessage.success("修改成功")
                })
            }
        }
        
}

const upStore=(row)=>{
    if(row.state==0){
        row.state=1
        ElMessage.error("切换为下架状态")
    }else{
        row.state=0
        ElMessage.success("切换为正常状态")
    }
    questionUpdate(row).then(res=>{
        getData()
    })
}

const handleSizeChange = (val) => {
getData()
}
const handleCurrentChange = (val) => {
getData()
}

</script>
<style scoped>
.answer-text {  
    white-space: nowrap; /* 防止文本换行 */  
    overflow: hidden; /* 隐藏超出部分 */  
    text-overflow: ellipsis; /* 显示省略号 */  
    width: 100%; /* 或指定一个具体的宽度，如 150px，取决于你的列宽 */  
    display: inline-block; /* 使得宽度和overflow属性生效 */  
}

.hoverColor:hover{
    color: rgb(56, 97, 0);
    font-size: 24px;
}
.hoverColor{
    font-size: 22px;
}
</style>